package com.libl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.libl.mapper.DtsAdminMapper;
import com.libl.mapper.DtsPermissionMapper;
import com.libl.mapper.DtsRoleMapper;
import com.libl.pojo.DtsAdmin;
import com.libl.pojo.DtsPermission;
import com.libl.pojo.DtsRole;
import com.libl.service.DtsRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
@Service
public class DtsRoleServiceImpl implements DtsRoleService {
    @Autowired
    DtsRoleMapper roleMapper;

    @Override
    public Set<String> findRolesByRoleIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsRole> wrapper = new LambdaQueryWrapper<>();
        //根据id使用 in查询
        wrapper.in(DtsRole::getId , roleIds);
        //查询没有被逻辑删除
        wrapper.eq(DtsRole::getDeleted, false);

        List<DtsRole> roleList = roleMapper.selectList(wrapper);

        //使用stream流进行转换数据
        Set<String> roles = roleList.stream().map((role) -> {
            return role.getName();
        }).collect(Collectors.toSet());

        return roles;
    }

    @Override
    public List<DtsRole> findAll() {
        //设置条件为当前角色未被逻辑删除
        LambdaQueryWrapper<DtsRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsRole::getDeleted, false);

        List<DtsRole> roleList = roleMapper.selectList(wrapper);
        return roleList;
    }

    @Override
    public Map<String, Object> queryPage(Integer page, Integer limit, String sort, String order, String rolename) {
        //分页条件
        IPage<DtsRole> ipage = new Page(page, limit);

        //其他查询条件
        QueryWrapper<DtsRole> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(rolename)) {
            wrapper.like("name", rolename);
        }
        if(!StringUtils.isEmpty(order) && !StringUtils.isEmpty(sort)) {
            if("desc".equals(order)){
                wrapper.orderByDesc(sort);
            }else{
                wrapper.orderByAsc(sort);
            }
        }

        roleMapper.selectPage(ipage, wrapper);

        //封装结果
        Map<String,Object> data = new HashMap<>();
        data.put("total", ipage.getTotal() );
        data.put("items", ipage.getRecords());
        return data;
    }

    @Override
    public void insert(DtsRole role) {
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        role.setDeleted(false);
        role.setEnabled(true);
        //执行新增
        roleMapper.insert(role);
    }

    // DO: 修改和删除
    @Override
    public void update(DtsRole role) {
        role.setUpdateTime(new Date());
        //执行修改
        roleMapper.updateById(role);
    }

    @Autowired
    DtsAdminMapper adminMapper;
    @Override
    public void delete(DtsRole role) {
        //判断是否被管理员所关联
        LambdaQueryWrapper<DtsAdmin> adminWrapper = new LambdaQueryWrapper<>();
        adminWrapper.select(DtsAdmin::getRoleIds);
        adminWrapper.eq(DtsAdmin::getDeleted,false);

        List<DtsAdmin> dtsAdmins = adminMapper.selectList(adminWrapper);
        //遍历
        for (DtsAdmin dtsAdmin : dtsAdmins) {
            Integer[] roleIds = dtsAdmin.getRoleIds();
            for (Integer roleId : roleIds) {
                if (roleId.equals(role.getId())){
                    throw new RuntimeException("该角色被管理员关联，无法删除！");
                }
            }
        }
        //判断是否被权限关联
        LambdaQueryWrapper<DtsPermission> permsWrapper = new LambdaQueryWrapper<>();
        permsWrapper.eq(DtsPermission::getRoleId,role.getId());
        permsWrapper.eq(DtsPermission::getDeleted,false);

        Integer count = permissionMapper.selectCount(permsWrapper);
        if (count>0){
            throw new RuntimeException("该角色已被权限关联，无法删除！");
        }

        // TODO: 2022/12/21 删除的时候不止要删除数据库中的数据，也要删除阿里云中的数据

    }



    @Override
    public boolean isSuperAdmin(Integer roleId) {
        DtsRole role = roleMapper.selectById(roleId);
        return role.getName().equals("超级管理员");
    }

    @Autowired
    DtsPermissionMapper permissionMapper;

    @Override
    public Set<String> queryStringPermissions(Integer roleId) {

        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(DtsPermission::getRoleId,roleId); // roleId = ?  ?若为一个值用eq，若为多个值用in
        wrapper.eq(DtsPermission::getDeleted,false);

        List<DtsPermission> permissionList = permissionMapper.selectList(wrapper);

        //使用stream流进行数据转换，list-->set
        Set<String> perms = permissionList.stream().map((permission) -> {
            return permission.getPermission();
        }).collect(Collectors.toSet());

        return perms;
    }

}
